package com.hzlx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzlx.bean.Inventory;
import com.hzlx.dao.InventoryDao;
import com.hzlx.dto.InventoryRequest;
import com.hzlx.dto.InventoryResponse;
import jakarta.annotation.Resource;
import jakarta.annotation.Resources;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class InventoryService {
    @Resource
    private final InventoryDao inventoryDao;
    @SneakyThrows
    public List<InventoryResponse> isInStock(List<String> skuCode) {

        log.info("Checking Inventory！查询！！！");
        QueryWrapper<Inventory> qw = Wrappers.<Inventory>query().in("sku", skuCode);
        return inventoryDao.selectList(qw)
                .stream()
                .map(inventory ->
                        InventoryResponse.builder()
                                .sku(inventory.getSku())
                                .isInStock(inventory.getQuantity() > 0 ? 1 : 0)//商品数量是否>0
                                .quantity(inventory.getQuantity())
                                .build()
                )
                .collect(Collectors.toList());
    }
    public void create(InventoryRequest request) {
        log.info("inventory inserted!添加！！！");
        Inventory inventory = Inventory.builder()
                .sku(request.getSku())
                .quantity(request.getQuantity())
                .isInStock(request.getQuantity() > 0 ? 1 : 0)
                .build();
        inventoryDao.insert(inventory);
        log.info("inventory inserted!添加成功！！！");
    }
    public void update(InventoryRequest request){
        log.info("inventory update!修改！！！");
        Inventory inventory = Inventory.builder()
                .sku(request.getSku())
                .quantity(request.getQuantity())
                .build();
        inventoryDao.update(inventory);
        log.info("inventory update!修改成功！！！");
    }
}
